package com.gdut.simple.model.impl;


import com.gdut.simple.common.RequestCallback;
import com.gdut.simple.data.entity.User;
import com.gdut.simple.model.IUpdateProfileModel;

import java.io.File;
import java.util.List;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadBatchListener;

public class UpdateProfileModelImpl implements IUpdateProfileModel {

    @Override
    public void update(final String imagePath, final RequestCallback<String> callback) {
        BmobFile.uploadBatch(new String[]{imagePath}, new UploadBatchListener() {
            @Override
            public void onSuccess(List<BmobFile> list, List<String> list1) {
                if (list.size() == 1) {
                    final User user = new User();
                    user.setProfile(list.get(0));
                    user.update(BmobUser.getCurrentUser(User.class).getObjectId(), new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            deleteTempFile(imagePath);
                            if (e == null) {
                                if (callback != null) {
                                    callback.onSuccess("");
                                }
                            } else {
                                if (callback != null) {
                                    callback.onFailure(e.getMessage());
                                }
                            }
                        }
                    });
                }
            }

            @Override
            public void onProgress(int i, int i1, int i2, int i3) {
            }

            @Override
            public void onError(int i, String s) {
                if (callback != null) {
                    callback.onFailure(s);
                }
            }
        });
    }

    private void deleteTempFile(String imagePath) {
        File file = new File(imagePath);
        if (file.exists()) {
            file.delete();
        }
    }
}
